package com.jiandan.asm

import org.gradle.api.Project
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import com.jiandan.asm.base.BaseTransform

class ASMTransform extends BaseTransform {

    Project project

    ASMTransform(Project project) {
        this.project = project
        //this.debounceExt = project."${DebounceExtension.NAME}"
    }

    @Override
    String getName() {
        return "AsmTransform"
    }

    @Override
    ClassVisitor getClassVisitor(ClassWriter classWriter) {
        return new ASMClassVisitor(classWriter)
    }

    @Override
    boolean isNeedTraceClass(File file) {
        def name = file.name
        if (!name.endsWith(".class")
                || name.startsWith("R.class")
                || name.startsWith('R$')) {
            return false
        }
        ASMExtension asmExtension = project.asmConfig
        //println(file.path)
        if (asmExtension != null) {
            if (!asmExtension.enabled) {
                return false
            }
            //优先使用include
            if (asmExtension.includes != null && asmExtension.includes.size() > 0) {
                FileInputStream inputStream = new FileInputStream(file)
                ClassReader classReader = new ClassReader(inputStream)
                String className = classReader.className.replaceAll("/", ".")
                boolean includeFile = false
                for (String packageName : asmExtension.includes) {
                    if (className.startsWith(packageName)) {
                        includeFile = true
                        break
                    }
                }
                //println("includes->" + className + " " + includeFile)
                return includeFile
            }
            if (asmExtension.excludes != null && asmExtension.excludes.size() > 0) {
                FileInputStream inputStream = new FileInputStream(file)
                ClassReader classReader = new ClassReader(inputStream)
                String className = classReader.className.replaceAll("/", ".")

                boolean includeFile = true
                for (String packageName : asmExtension.excludes) {

                    if (className.startsWith(packageName)) {
                        includeFile = false
                        break
                    }
                }
               // println("excludes->" + className + " " + includeFile)
                return includeFile
            }
        }
        return true
    }
}